import React, { useEffect, useState } from 'react';

const emptyForm = { title: '', video_url: '', content: '', images: '' };

const ContentManager = () => {
  const [contents, setContents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [editing, setEditing] = useState(null);
  const [token] = useState(localStorage.getItem('token'));

  const fetchContents = async () => {
    setLoading(true);
    const res = await fetch('/api/contents');
    const data = await res.json();
    setContents(data.contents || []);
    setLoading(false);
  };

  useEffect(() => {
    fetchContents();
  }, []);

  const handleInput = e => {
    setForm({ ...form, [e.target.name]: e.target.value });
  };

  const handleSubmit = async e => {
    e.preventDefault();
    if (!form.title) return alert('标题必填');
    const method = editing ? 'PUT' : 'POST';
    const url = editing ? `/api/contents/${editing.id}` : '/api/contents';
    await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        ...form
      })
    });
    setForm(emptyForm);
    setEditing(null);
    fetchContents();
  };

  const handleEdit = item => {
    setEditing(item);
    setForm({
      title: item.title,
      video_url: item.video_url || '',
      content: item.content || '',
      images: item.images ? item.images.join(',') : ''
    });
  };

  const handleDelete = async id => {
    if (!window.confirm('确定要删除该内容吗？')) return;
    await fetch(`/api/contents/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    });
    fetchContents();
  };

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', background: '#fff', borderRadius: 16, boxShadow: '0 4px 24px #e3e8f0', padding: 32 }}>
      <h2 style={{ marginBottom: 24, color: '#6a82fb', letterSpacing: 2 }}>内容管理</h2>
      <form onSubmit={handleSubmit} style={{ marginBottom: 28, display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center', background: '#f7f9fa', borderRadius: 10, padding: 18 }}>
        <input name="title" value={form.title} onChange={handleInput} placeholder="标题" required style={{ width: 160, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <input name="video_url" value={form.video_url} onChange={handleInput} placeholder="视频URL" style={{ width: 180, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <input name="images" value={form.images} onChange={handleInput} placeholder="图片URL，逗号分隔" style={{ width: 220, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <textarea name="content" value={form.content} onChange={handleInput} placeholder="内容" rows={2} style={{ width: 220, border: '1px solid #e3e8f0', borderRadius: 6, padding: 8 }} />
        <button type="submit" style={{ background: '#6a82fb', color: '#fff', border: 0, borderRadius: 6, padding: '8px 24px', fontWeight: 600, letterSpacing: 1 }}>{editing ? '保存' : '添加'}</button>
        {editing && <button type="button" onClick={() => { setEditing(null); setForm(emptyForm); }} style={{ marginLeft: 8, background: '#eee', border: 0, borderRadius: 6, padding: '8px 18px' }}>取消</button>}
      </form>
      <div style={{ marginTop: 18 }}>
        {loading ? '加载中...' : contents.length === 0 ? '暂无内容' : contents.map(item => (
          <div key={item.id} style={{ border: '1px solid #e3e8f0', borderRadius: 10, marginBottom: 24, padding: 18, background: '#f7f9fa' }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
              <div style={{ fontWeight: 600, fontSize: 18, color: '#6a82fb', flex: 1 }}>{item.title}</div>
              <button onClick={() => handleEdit(item)} style={{ marginRight: 8, background: '#e6edfa', color: '#6a82fb', border: 0, borderRadius: 6, padding: '5px 14px', fontWeight: 500 }}>编辑</button>
              <button onClick={() => handleDelete(item.id)} style={{ background: '#fc5c7d', color: '#fff', border: 0, borderRadius: 6, padding: '5px 14px', fontWeight: 500 }}>删除</button>
            </div>
            {item.video_url && (
              <div style={{ margin: '8px 0' }}>
                <video src={item.video_url} controls style={{ maxWidth: 320, borderRadius: 8 }} />
              </div>
            )}
            <div style={{ margin: '8px 0', color: '#444' }}>{item.content}</div>
            {item.images && item.images.length > 0 && (
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', margin: '8px 0' }}>
                {item.images.map((img, idx) => (
                  <img key={idx} src={img} alt="img" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 6, border: '1px solid #eee' }} />
                ))}
              </div>
            )}
            {item.comments && item.comments.length > 0 && (
              <div style={{ marginTop: 10, background: '#fff', borderRadius: 8, padding: 10, boxShadow: '0 1px 4px #eee' }}>
                <div style={{ fontWeight: 500, color: '#6a82fb', marginBottom: 6 }}>评论：</div>
                {item.comments.map(c => (
                  <div key={c.id} style={{ borderBottom: '1px solid #f0f0f0', padding: '6px 0', color: '#444' }}>
                    <span style={{ color: '#888', marginRight: 8 }}>{c.author || '匿名'}：</span>
                    {c.comment}
                  </div>
                ))}
              </div>
            )}
            <div style={{ color: '#aaa', fontSize: 13, marginTop: 6 }}>创建时间：{item.created_at?.slice(0, 19).replace('T', ' ')}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ContentManager; 